#include "mq_send_receive.h"

/**
 * 参数：name:为队列的名字
 * 功能：创建一个消息队列，并返回队列的描述符
 */
mqd_t create_message_queue(char *name){
    struct mq_attr arr;
    arr.mq_curmsgs = 0;
    arr.mq_maxmsg = 10;
    arr.mq_msgsize = MAX_MSG_SIZE;
    arr.mq_flags = 0;
    
    mqd_t mqd_send = mq_open(name, O_CREAT | O_RDWR, 0666, &arr);
    if (mqd_send == -1) {
        perror("mq_open");
        exit(1);
    }
    return mqd_send;
}

/**
 * 参数：name:为队列的名字
 * 功能：使用一个消息队列，并返回队列的描述符
 */
mqd_t open_message_queue(char *name) {
    mqd_t mqd_receive = mq_open(name, O_RDWR, 0666);
    if (mqd_receive == (mqd_t)-1) {
        perror("mq_open");
        exit(1);
    }
    return mqd_receive;
}
/**
 * 参数：mqd_send:为队列的描述符，msg:为要发送的消息,time:最多等待多少秒发送
 * 功能：向队列发送消息
 * return:成功返回0，失败返回-1
 */
int send_buf(mqd_t mqd_send, char *msg,char time){
    struct timespec ts;
    clock_gettime(0, &ts);
    ts.tv_sec += time;
    if (mq_timedsend(mqd_send, msg, strlen(msg),0, &ts)==-1) {
        perror("mq_send");
        return -1;
    }
    
    return 0;
}

/**
 * 参数：mqd_receive:为队列的描述符,msg:为接收到的消息,time:最多等待多少秒接收
 * 功能：从队列接收消息
 * return:成功返回0，失败返回-1
 */
int receive_buf(mqd_t mqd_receive,char *msg,char time){
    struct timespec ts;
    clock_gettime(0, &ts);
    ts.tv_sec += time;

    if (mq_timedreceive(mqd_receive, msg, MAX_MSG_SIZE, NULL,&ts)==-1) {
        perror("mq_receive");
        return -1;
    }
    return 0;
}